package com.hakim.wfb.customer.service.biz;

import com.alibaba.fastjson.JSON;
import com.hakim.wfb.biz.CreditPointBiz;
import com.hakim.wfb.biz.PointOrderBiz;
import com.hakim.wfb.biz.UserBiz;
import com.hakim.wfb.common.enums.PointTypeEnum;
import com.hakim.wfb.common.enums.WalletResponseResultEnum;
import com.hakim.wfb.common.util.SignUtils;
import com.hakim.wfb.customer.constant.Constants;
import com.hakim.wfb.customer.params.trans.CalculatePointWithdrawParameter;
import com.hakim.wfb.customer.params.wallet.GenerateUserWalletParameter;
import com.hakim.wfb.customer.params.wallet.WithdrawWalletParam;
import com.hakim.wfb.customer.result.trans.PointWithdrawCalculateView;
import com.hakim.wfb.customer.result.wallet.UserWalletAddressResult;
import com.hakim.wfb.customer.result.wallet.WalletWithdrawResult;
import com.hakim.wfb.dao.WithdrawAddrDao;
import com.hakim.wfb.dao.WithdrawRecordDao;
import com.hkfs.fundamental.api.data.ObjectResultEx;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2017/7/10.
 */
@Service("withdrawBizService")
public class WithdrawBizService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserBiz userBiz;

    @Autowired
    private CreditPointBiz creditPointBiz;

    @Autowired
    private PointOrderBiz pointOrderBiz;

    @Autowired
    private WithdrawRecordDao withdrawRecordDao;

    @Autowired
    private WithdrawAddrDao withdrawAddrDao;

    /**
     * 调用钱包接口生成用户钱包接口
     */
    public ObjectResultEx<UserWalletAddressResult> generateUserWallet(
            GenerateUserWalletParameter param) {

        ObjectResultEx<UserWalletAddressResult> resultEx = new ObjectResultEx<>();
        //构建签名map
        Map<String, String> signMap = new HashMap<>();
        signMap.put("userid", param.getWalletId().toString());
        // 对参数进行签名
        String sign = SignUtils.createSign(signMap, Constants.BLOCKCHAIN_SIGN_KEY);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        NameValuePair addressNV = new BasicNameValuePair("userid", param.getWalletId().toString());
        NameValuePair signNV = new BasicNameValuePair("sign", sign);
        nameValuePairs.add(addressNV);
        nameValuePairs.add(signNV);
        ObjectResultEx<String> objectResultEx = postRequest(
                Constants.BLOCKCHAIN_GETUSER_ADDRESS_URL, nameValuePairs);
        if (objectResultEx.isSuccess()) {

            String responseXml = objectResultEx.getDataObject();
            UserWalletAddressResult userWalletAddressResult = JSON
                    .parseObject(responseXml, UserWalletAddressResult.class);
            if (userWalletAddressResult != null &&
                    userWalletAddressResult.getState()
                            .equals(WalletResponseResultEnum.SUCCESS.getValue())) {
                resultEx.setDataObject(userWalletAddressResult);
                resultEx.makeSuccessResult();
            } else {
                resultEx.makeFailedResult();
            }
        } else {
            resultEx.makeFailedResult();
        }
        return resultEx;
    }

    /**
     * 调用钱包提币
     */
    public ObjectResultEx<WalletWithdrawResult> withdrawWallet(WithdrawWalletParam param) {

        ObjectResultEx<WalletWithdrawResult> resultEx = new ObjectResultEx();
        Map<String, String> signMap = new HashMap<>();
        signMap.put("address", param.getAddress().toString());
        signMap.put("amount", param.getAmount().toString());
        String sign = SignUtils.createSign(signMap, Constants.BLOCKCHAIN_SIGN_KEY);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        NameValuePair addressNV = new BasicNameValuePair("address", param.getAddress());
        NameValuePair amountNV = new BasicNameValuePair("amount", param.getAmount().toString());
        NameValuePair signNV = new BasicNameValuePair("sign", sign);
        nameValuePairs.add(addressNV);
        nameValuePairs.add(amountNV);
        nameValuePairs.add(signNV);
        ObjectResultEx<String> objectResultEx = postRequest(Constants.BLOCKCHAIN_WITHDRAW_URL,
                nameValuePairs);
        if (objectResultEx.isSuccess()) {
            String responseXml = objectResultEx.getDataObject();
            WalletWithdrawResult walletWithdrawResult = JSON
                    .parseObject(responseXml, WalletWithdrawResult.class);
            if (walletWithdrawResult != null) {
                if (walletWithdrawResult.getState()
                        .equals(WalletResponseResultEnum.SUCCESS.getValue())) {
                    resultEx.setDataObject(walletWithdrawResult);
                    return resultEx.makeSuccessResult();
                } else {
                    resultEx.setRetMsg(walletWithdrawResult.getError());
                    return resultEx.makeFailedResult();
                }
            }
        }
        return resultEx.makeFailedResult();
    }

    /**
     * https请求钱包
     *
     * @param url 请求地址
     * @param nameValuePairs 请求的xml参数
     */
    private ObjectResultEx<String> postRequest(String url, List<NameValuePair> nameValuePairs) {
        ObjectResultEx<String> resultEx = new ObjectResultEx<>();
        if (StringUtils.isEmpty(url)) {
            logger.error("请求地址或者请求参数为空：{}", url);
            return resultEx.makeFailedResult("请求地址或者请求参数为空");
        }
        try {
            // 发送请求微信接口
            String resultXml = Request.Post(url)
                    .bodyForm(nameValuePairs)
                    .execute().returnContent().asString();
            logger.info("钱包接口请求响应结果：{}", resultXml);
            resultEx.setDataObject(resultXml);
            return resultEx.makeSuccessResult();
        } catch (Exception e) {
            logger.error("请求钱包接口异常", e);
            return resultEx.makeFailedResult("请求钱包接口异常");
        }
    }

    /**
     * @param param
     * @return
     */
    public ObjectResultEx<PointWithdrawCalculateView> calculateWithdrawPoint(
            CalculatePointWithdrawParameter param) {

        ObjectResultEx<PointWithdrawCalculateView> resultEx = new ObjectResultEx();
        PointTypeEnum pointType = PointTypeEnum.getByValue(param.getPointType());
        if (pointType == null) {
            resultEx.makeFailedResult("积分类型无效");
        }
        PointWithdrawCalculateView pointWithdrawCalculateView = new PointWithdrawCalculateView();

        //相应积分类型减少
        if (pointType.getValue() == PointTypeEnum.ORIGINAL_POINT.getValue()
                || pointType.getValue() == PointTypeEnum.REPEAT_POINT.getValue()) {

            //实际能提取到交易网的数量
            pointWithdrawCalculateView.setWithdrawablePointAmount(
                    param.getPointAmount().multiply(BigDecimal.valueOf(0.8)));
            pointWithdrawCalculateView
                    .setPointReusable(param.getPointAmount().multiply(BigDecimal.valueOf(0.15)));
            pointWithdrawCalculateView
                    .setPointFoundation(param.getPointAmount().multiply(BigDecimal.valueOf(0.05)));
        } else if (pointType.getValue() == PointTypeEnum.STATIC_POINT.getValue()
                || pointType.getValue() == PointTypeEnum.DYNAMIC_POINT.getValue()) {

            pointWithdrawCalculateView.setWithdrawablePointAmount(
                    param.getPointAmount().multiply(BigDecimal.valueOf(0.7)));
            pointWithdrawCalculateView
                    .setPointReusable(param.getPointAmount().multiply(BigDecimal.valueOf(0.2)));
            pointWithdrawCalculateView
                    .setPointFee(param.getPointAmount().multiply(BigDecimal.valueOf(0.05)));
            pointWithdrawCalculateView
                    .setPointFoundation(param.getPointAmount().multiply(BigDecimal.valueOf(0.05)));
        } else {
            resultEx.setRetMsg("不支持" + pointType.getDescription() + "提现");
            return resultEx.makeFailedResult();
        }
        resultEx.setDataObject(pointWithdrawCalculateView);
        return resultEx.makeSuccessResult();
    }

}
